package com.danger.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.danger.model.entity.Song;
import com.danger.presenter.PlayPresenter;
import com.danger.presenter.PlayPresenterImpl;
import com.danger.service.KeepLiveService;
import com.danger.service.PlayServiceImpl;
import com.danger.util.AnimationUtil;
import com.danger.util.Constant;
import com.danger.util.TimeUtil;
import com.danger.view.PlayView;
import com.danger.view.adapter.SongAdapter;
import com.danger.widget.MarqueeTextView;
import com.danger.widget.MyCircleImageView;
import com.danger.widget.PlayerPopupWindow;

import java.io.Serializable;
import java.util.List;

public class MainActivity extends BaseActivity implements PlayView, View.OnClickListener {

    private ListView song_listView;
    private LinearLayout play_layout;
    private MyCircleImageView artist_photo_imageView;
    private MarqueeTextView song_name_textView;
    private MarqueeTextView artist_name_textView;
    private ImageButton previous_song_button;
    private ImageButton play_song_button;
    private ImageButton next_song_button;
    private static final int REQUEST_CODE = 1;
    private ProgressDialog dialog;
    private PlayPresenter presenter;
    private List<Song> songs;
    private PlayerPopupWindow popupWindow;
    private MyBroadcastReceiver receiver;
    private Animation animation;
    private AnimationUtil animationUtil;
    private KeepLiveReceiver keepLiveReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);
            return;
        } else {
            bindView();
            bindEvent();
        }
    }

    @Override
    public void bindView() {
        song_listView = (ListView) findViewById(R.id.song_listView);
        play_layout = (LinearLayout) findViewById(R.id.play_layout);
        artist_photo_imageView = (MyCircleImageView) findViewById(R.id.artist_photo_imageView);
        song_name_textView = (MarqueeTextView) findViewById(R.id.song_name_textView);
        artist_name_textView = (MarqueeTextView) findViewById(R.id.artist_name_textView);
        previous_song_button = (ImageButton) findViewById(R.id.previous_song_button);
        play_song_button = (ImageButton) findViewById(R.id.play_song_button);
        next_song_button = (ImageButton) findViewById(R.id.next_song_button);
        play_song_button.setBackgroundResource(R.drawable.play);
        animation = AnimationUtils.loadAnimation(this, R.anim.main_photo_rotate);
        animation.setInterpolator(new LinearInterpolator());
        animationUtil = new AnimationUtil(artist_photo_imageView, animation);
        receiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter(Constant.UPDATE_UI);
        registerReceiver(receiver, filter);
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在扫描...");
        presenter = new PlayPresenterImpl(this, this);
        presenter.scanSongs();

        keepLiveReceiver = new KeepLiveReceiver();
        IntentFilter filter1 = new IntentFilter();
        filter1.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(keepLiveReceiver, filter1);
    }

    @Override
    public void bindEvent() {
        previous_song_button.setOnClickListener(this);
        play_song_button.setOnClickListener(this);
        next_song_button.setOnClickListener(this);
        play_layout.setOnClickListener(this);
        song_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, PlayServiceImpl.class);
                intent.putExtra("position", position);
                intent.putExtra("songs", (Serializable) songs);
                intent.setAction(Constant.PLAY_MSG);
                startService(intent);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "获取读写权限失败", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    bindView();
                    bindEvent();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void showLoading() {
        dialog.show();
    }

    @Override
    public void hideLoading() {
        dialog.dismiss();
    }

    @Override
    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showSongs(List<Song> songs) {
        Log.i("songs", songs.toString());
        if (songs != null) {
            this.songs = songs;
            SongAdapter adapter = new SongAdapter(this, songs);
            song_listView.setAdapter(adapter);
            setDefaultPlay();
            Intent intent = new Intent(MainActivity.this, PlayServiceImpl.class);
            intent.setAction(Constant.PAUSE_MSG);
            startService(intent);
        } else {
            showMessage("没有歌曲...");
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, PlayServiceImpl.class);
        switch (v.getId()) {
            case R.id.previous_song_button:
                intent.setAction(Constant.PREVIOUS_MSG);
                startService(intent);
                break;
            case R.id.play_song_button:
                intent.setAction(Constant.PAUSE_MSG);
                startService(intent);
                break;
            case R.id.next_song_button:
                intent.setAction(Constant.NEXT_MSG);
                startService(intent);
                break;
            case R.id.play_layout:
                play_layout.setVisibility(View.GONE);
                popupWindow.showAsDropDown(play_layout, 0, 0);
                popupWindow.setAnimationStyle(R.style.popupwindow_anim);
                Log.i("popup", "------" + popupWindow.isShowing());
                break;
            default:
                break;
        }
    }


    private void setDefaultPlay() {
        popupWindow = new PlayerPopupWindow(this, play_layout);
        Log.i("popup", "------" + popupWindow.isShowing());
        Intent intent = new Intent(MainActivity.this, PlayServiceImpl.class);
        intent.putExtra("songs", (Serializable) songs);
        intent.putExtra("position", 0);
        intent.setAction(Constant.PLAY_MSG);
        startService(intent);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateUI(intent);
        }
    }

    private void updateUI(Intent intent) {
        int type = intent.getIntExtra("type", 0);
        //播放
        if (type == 1) {
            int position = intent.getIntExtra("position", 0);
            Song song = songs.get(position);
            song_name_textView.setText(song.getName());
            artist_name_textView.setText(song.getArtist());
            animationUtil.startAnimation();
            play_song_button.setBackgroundResource(R.drawable.pause);
            if (popupWindow != null) {
                popupWindow.getNameTextView().setText(song.getName());
                popupWindow.getArtistTextView().setText("- " + song.getArtist() + " -");
                popupWindow.getPlaySongButton().setBackgroundResource(R.drawable.pause);
                popupWindow.getRightTextView().setText(TimeUtil.parseDuration(song.getDuration()));
            }
            //暂停
        } else if (type == 2) {
            play_song_button.setBackgroundResource(R.drawable.play);
            if (popupWindow != null) {
                popupWindow.getPlaySongButton().setBackgroundResource(R.drawable.play);
            }
            //重新恢复播放
        } else if (type == 3) {
            play_song_button.setBackgroundResource(R.drawable.pause);
            if (popupWindow != null) {
                popupWindow.getPlaySongButton().setBackgroundResource(R.drawable.pause);
            }
            //更新进度条
        } else if (type == 4) {
            if (popupWindow != null) {
                float finished = intent.getLongExtra("progress", 0);
                float length = intent.getLongExtra("length", 0);
                int progress = (int) ((finished / length) * 100);
                popupWindow.getSeekBar().setProgress(progress);
                popupWindow.getLeftTextView().setText(TimeUtil.parseDuration((long) finished));
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Intent intent = new Intent(MainActivity.this, PlayServiceImpl.class);
        intent.setAction(Constant.NOTIFICATION);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void onBackPressed() {
        play_layout.setVisibility(View.VISIBLE);
        super.onBackPressed();
    }

    public class KeepLiveReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                Intent live_intent = new Intent(context, KeepLiveActivity.class);
                live_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(live_intent);
            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                sendBroadcast(new Intent("finish"));
            }
            Intent service_intent = new Intent(context, KeepLiveService.class);
            startService(service_intent);
        }
    }


}